﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MMOArpgServer.DAL
{
    public abstract class AbsCachePool : ICachePool
    {

        protected Dictionary<object, AbsCacheData> _CachePool = new Dictionary<object, AbsCacheData>();
        protected Queue<AbsCacheData> _FreeCachePool = new Queue<AbsCacheData>();
        public virtual AbsCacheData GetCacheByKey(object key)
        {
            AbsCacheData temp=null;
            if (_CachePool.Count > 0)
            {
                try
                {
                    if (_CachePool.ContainsKey(key)) {
                        temp = _CachePool[key];
                    }
                }
                catch (Exception e) {
                    Console.WriteLine(e.Message);
                }
            }
            else {
                temp = null;
            }
            return temp;
        }

        public virtual object GetKeyByCache(AbsCacheData cache)
        {
            return _CachePool.First(temp => temp.Value == cache).Key;
        }

        public virtual void AddCacheToPool(object key, AbsCacheData cache)
        {
            _CachePool.Add(key, cache);
        }

        public virtual void RemoveCache(object key)
        {
            AbsCacheData temp = GetCacheByKey(key);
            temp.Release();
            _CachePool.Remove(key);
            _FreeCachePool.Enqueue(temp);
        }

        public virtual AbsCacheData GetFreeCache()
        {
            if (_FreeCachePool.Count > 0)
            {
                return _FreeCachePool.Dequeue();
            }
            else {
                return null;
            }
        }

        public virtual void Release()
        {
            foreach (var temp in _CachePool) {
                temp.Value.Release();
            }
        }
    }
}
